<template>
<!-- 政策附件管理 -->
      <div class="policy-attachment-container">
        <!-- 搜索栏 -->
        <div class="search-container">
          <el-form :model="searchForm" class="search-form" label-width="80px">
            <el-row :gutter="20">
              <el-col :xs="24" :sm="12" :md="8" :lg="6">
                <el-form-item label="政策ID">
                  <el-input
                    v-model.number="searchForm.policyId"
                    placeholder="请输入政策ID"
                    clearable
                  />
                </el-form-item>
              </el-col>
              
              <el-col :xs="24" :sm="12" :md="8" :lg="6">
                <el-form-item label="附件名称">
                  <el-input
                    v-model="searchForm.attachmentName"
                    placeholder="请输入附件名称"
                    clearable
                  />
                </el-form-item>
              </el-col>
              
              <el-col :xs="24" :sm="12" :md="8" :lg="6">
                <el-form-item label="附件类型">
                  <el-input
                    v-model="searchForm.attachmentType"
                    placeholder="请输入附件类型"
                    clearable
                  />
                </el-form-item>
              </el-col>
              
              <el-col :xs="24" :sm="12" :md="8" :lg="6">
                <el-form-item label="上传人">
                  <el-input
                    v-model="searchForm.uploaderName"
                    placeholder="请输入上传人姓名"
                    clearable
                  />
                </el-form-item>
              </el-col>
              
              <el-col :xs="24" :sm="24" :md="24" :lg="6" class="search-buttons">
                <el-button type="primary" @click="handleSearch">
                  <i class="el-icon-search"></i> 搜索
                </el-button>
                <el-button @click="resetSearch">
                  <i class="el-icon-refresh"></i> 重置
                </el-button>
              </el-col>
            </el-row>
          </el-form>
        </div>

        <!-- 操作按钮 -->
        <div class="operation-buttons">
          <el-button type="primary" @click="handleUpload">
            <i class="el-icon-upload2"></i> 上传附件
          </el-button>
          <el-button type="danger" @click="handleBatchDelete" :disabled="!selectedIds.length">
            <i class="el-icon-delete"></i> 批量删除
          </el-button>
        </div>

        <!-- 表格 -->
        <div class="table-container">
          <el-table
            :data="tableData"
            border
            stripe
            style="width: 100%"
            @selection-change="handleSelectionChange"
            v-loading="loading"
            element-loading-text="数据加载中..."
            :header-cell-style="{ background: '#f5f7fa', color: '#606266', fontWeight: 'bold' }"
          >
            <el-table-column type="selection" width="55" align="center" />
            
            <el-table-column prop="attachmentId" label="附件ID" width="100" align="center" />
            
            <el-table-column prop="policyId" label="政策ID" width="100" align="center" />
            
            <el-table-column prop="attachmentName" label="附件名称" width="180" align="center">
              <template #default="{ row }">
                <el-link type="primary" @click="downloadAttachment(row)">{{ row.attachmentName }}</el-link>
              </template>
            </el-table-column>
            
            <el-table-column prop="attachmentSize" label="附件大小" width="120" align="center">
              <template #default="{ row }">
                {{ formatFileSize(row.attachmentSize) }}
              </template>
            </el-table-column>
            
            <el-table-column prop="attachmentType" label="附件类型" width="120" align="center" />
            
            <el-table-column prop="attachmentPath" label="附件路径" width="250" align="center">
              <template #default="{ row }">
                <span class="ellipsis" :title="row.attachmentPath">{{ row.attachmentPath }}</span>
              </template>
            </el-table-column>
            
            <el-table-column prop="createTime" label="创建时间" width="180" align="center">
              <template #default="{ row }">
                {{ formatDate(row.createTime) }}
              </template>
            </el-table-column>
            
            <el-table-column prop="uploaderId" label="上传人ID" width="120" align="center" />
            
            <el-table-column prop="uploaderName" label="上传人姓名" width="120" align="center" />
            
            <el-table-column label="操作" width="200" align="center" fixed="right">
              <template #default="{ row }">
                <el-button size="mini" type="primary" plain @click="handleEdit(row)">
                  <i class="el-icon-edit"></i> 编辑
                </el-button>
                <el-button size="mini" type="danger" plain @click="handleDelete(row)">
                  <i class="el-icon-delete"></i> 删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>

          <!-- 分页 -->
          <div class="pagination-container">
            <el-pagination
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
              :current-page="pagination.currentPage"
              :page-sizes="[10, 20, 50, 100]"
              :page-size="pagination.pageSize"
              layout="total, sizes, prev, pager, next, jumper"
              :total="pagination.total"
            />
          </div>
        </div>

        <!-- 上传对话框 -->
        <el-dialog 
          :title="dialogTitle" 
          v-model="uploadDialogVisible" 
          width="500px" 
          :close-on-click-modal="false"
        >
          <el-form :model="uploadForm" ref="uploadFormRef" label-width="120px">
            <el-form-item label="政策ID" prop="policyId">
              <el-input 
                type="number" 
                v-model.number="uploadForm.policyId" 
                placeholder="请输入政策ID"
                clearable
              />
            </el-form-item>
            
            <el-form-item label="上传人ID" prop="uploaderId">
              <el-input 
                type="number" 
                v-model.number="uploadForm.uploaderId" 
                placeholder="请输入上传人ID"
                clearable
              />
            </el-form-item>
            
            <el-form-item label="上传人姓名" prop="uploaderName">
              <el-input 
                v-model="uploadForm.uploaderName" 
                placeholder="请输入上传人姓名"
                clearable
              />
            </el-form-item>
            
            <el-form-item label="上传附件" prop="file">
              <el-upload
                class="upload-demo"
                ref="uploadRef"
                action="https://jsonplaceholder.typicode.com/posts/"
                :show-file-list="false"
                :on-success="handleUploadSuccess"
                :on-error="handleUploadError"
                :before-upload="beforeUpload"
              >
                <el-button size="small" type="primary">选择文件</el-button>
                <div v-if="uploadForm.fileName" class="el-upload__tip">
                  已选择文件: {{ uploadForm.fileName }}
                </div>
              </el-upload>
            </el-form-item>
          </el-form>
          
          <template #footer>
            <div class="dialog-footer">
              <el-button @click="uploadDialogVisible = false">
                <i class="el-icon-close"></i> 取消
              </el-button>
              <el-button type="primary" @click="submitUpload">
                <i class="el-icon-upload2"></i> 上传
              </el-button>
            </div>
          </template>
        </el-dialog>

        <!-- 编辑对话框 -->
        <el-dialog 
          :title="dialogTitle" 
          v-model="editDialogVisible" 
          width="500px" 
          :close-on-click-modal="false"
        >
          <el-form :model="editForm" :rules="editRules" ref="editFormRef" label-width="120px">
            <el-form-item label="附件ID" prop="attachmentId">
              <el-input 
                disabled
                v-model="editForm.attachmentId" 
              />
            </el-form-item>
            
            <el-form-item label="政策ID" prop="policyId">
              <el-input 
                type="number" 
                v-model.number="editForm.policyId" 
                placeholder="请输入政策ID"
                clearable
              />
            </el-form-item>
            
            <el-form-item label="上传人ID" prop="uploaderId">
              <el-input 
                type="number" 
                v-model.number="editForm.uploaderId" 
                placeholder="请输入上传人ID"
                clearable
              />
            </el-form-item>
            
            <el-form-item label="上传人姓名" prop="uploaderName">
              <el-input 
                v-model="editForm.uploaderName" 
                placeholder="请输入上传人姓名"
                clearable
              />
            </el-form-item>
            
            <el-form-item label="附件名称" prop="attachmentName">
              <el-input 
                v-model="editForm.attachmentName" 
                placeholder="请输入附件名称"
                clearable
              />
            </el-form-item>
            
            <el-form-item label="附件类型" prop="attachmentType">
              <el-input 
                v-model="editForm.attachmentType" 
                placeholder="请输入附件类型"
                clearable
              />
            </el-form-item>
            
            <el-form-item label="附件路径" prop="attachmentPath">
              <el-input 
                v-model="editForm.attachmentPath" 
                placeholder="请输入附件路径"
                clearable
              />
            </el-form-item>
            
            <el-form-item label="附件大小" prop="attachmentSize">
              <el-input 
                v-model="editForm.attachmentSize" 
                placeholder="请输入附件大小"
                clearable
              />
            </el-form-item>
          </el-form>
          
          <template #footer>
            <div class="dialog-footer">
              <el-button @click="editDialogVisible = false">
                <i class="el-icon-close"></i> 取消
              </el-button>
              <el-button type="primary" @click="submitEdit">
                <i class="el-icon-check"></i> 确定
              </el-button>
            </div>
          </template>
        </el-dialog>
      </div>
    </template>

    <script>
    import request from '@/utils/request';
    import { formatDate, formatFileSize } from '@/utils/date';

    export default {
      name: 'PolicyAttachmentManagement',
      data() {
        return {
          // 搜索表单
          searchForm: {
            policyId: null,
            attachmentName: '',
            attachmentType: '',
            uploaderName: ''
          },
          
          // 表格数据
          tableData: [],
          loading: false,
          selectedIds: [],
          
          // 分页配置
          pagination: {
            currentPage: 1,
            pageSize: 10,
            total: 0
          },
          
          // 上传对话框配置
          uploadDialogVisible: false,
          uploadForm: {
            policyId: null,
            uploaderId: null,
            uploaderName: '',
            file: null,
            fileName: ''
          },
          
          // 编辑对话框配置
          editDialogVisible: false,
          dialogTitle: '上传附件',
          editForm: {
            attachmentId: null,
            policyId: null,
            uploaderId: null,
            uploaderName: '',
            attachmentName: '',
            attachmentType: '',
            attachmentPath: '',
            attachmentSize: '',
            createTime: null
          },
          
          // 编辑表单验证规则
          editRules: {
            policyId: [
              { required: true, message: '请输入政策ID', trigger: 'blur' },
              { type: 'number', message: '请输入数字', trigger: 'blur' }
            ],
            uploaderId: [
              { required: true, message: '请输入上传人ID', trigger: 'blur' },
              { type: 'number', message: '请输入数字', trigger: 'blur' }
            ],
            uploaderName: [
              { required: true, message: '请输入上传人姓名', trigger: 'blur' },
              { min: 1, message: '上传人姓名不能为空', trigger: 'blur' }
            ],
            attachmentName: [
              { required: true, message: '请输入附件名称', trigger: 'blur' },
              { min: 1, message: '附件名称不能为空', trigger: 'blur' }
            ],
            attachmentType: [
              { required: true, message: '请输入附件类型', trigger: 'blur' },
              { min: 1, message: '附件类型不能为空', trigger: 'blur' }
            ],
            attachmentPath: [
              { required: true, message: '请输入附件路径', trigger: 'blur' },
              { min: 1, message: '附件路径不能为空', trigger: 'blur' }
            ],
            attachmentSize: [
              { required: true, message: '请输入附件大小', trigger: 'blur' },
              { min: 1, message: '附件大小不能为空', trigger: 'blur' }
            ]
          }
        };
      },
      
      methods: {
        // 格式化日期
        formatDate(date, format = 'YYYY-MM-DD HH:mm:ss') {
          return formatDate(date, format);
        },
        
        // 格式化文件大小
        formatFileSize(bytes) {
          if (bytes === null || bytes === undefined || bytes === '') return '';
          bytes = parseInt(bytes);
          if (isNaN(bytes)) return '';
          
          const units = ['B', 'KB', 'MB', 'GB', 'TB'];
          let size = bytes;
          let unitIndex = 0;
          
          while (size >= 1024 && unitIndex < units.length - 1) {
            size /= 1024;
            unitIndex++;
          }
          
          return `${size.toFixed(2)} ${units[unitIndex]}`;
        },
        
        // 获取数据列表
        fetchData() {
          this.loading = true;
          request.get('/policyAttachment/list', {
            params: {
              current: this.pagination.currentPage,
              size: this.pagination.pageSize,
              ...this.searchForm
            }
          })
            .then(res => {
              if (res.code === 200) {
                this.tableData = res.data.records;
                this.pagination.total = res.data.total;
              } else {
                this.$message.error(res.message || '获取政策附件列表失败');
              }
            })
            .catch(err => {
              console.error('获取政策附件列表失败:', err);
              this.$message.error('加载政策附件列表失败');
            })
            .finally(() => {
              this.loading = false;
            });
        },
        
        // 搜索处理
        handleSearch() {
          this.pagination.currentPage = 1;
          this.fetchData();
        },
        
        // 重置搜索
        resetSearch() {
          this.searchForm = {
            policyId: null,
            attachmentName: '',
            attachmentType: '',
            uploaderName: ''
          };
          this.handleSearch();
        },
        
        // 选择行变更
        handleSelectionChange(selection) {
          this.selectedIds = selection.map(item => item.attachmentId);
        },
        
        // 分页大小变更
        handleSizeChange(val) {
          this.pagination.pageSize = val;
          this.fetchData();
        },
        
        // 当前页变更
        handleCurrentChange(val) {
          this.pagination.currentPage = val;
          this.fetchData();
        },
        
        // 上传附件
        handleUpload() {
          this.dialogTitle = '上传附件';
          this.uploadForm = {
            policyId: null,
            uploaderId: null,
            uploaderName: '',
            file: null,
            fileName: ''
          };
          this.uploadDialogVisible = true;
        },
        
        // 编辑附件
        handleEdit(row) {
          this.dialogTitle = '编辑附件';
          this.editForm = {
            ...row
          };
          this.editDialogVisible = true;
        },
        
        // 删除附件
        handleDelete(row) {
          this.$confirm(`确认删除附件「${row.attachmentName}」吗？`, '提示', {
            type: 'warning',
            confirmButtonText: '确认删除',
            cancelButtonText: '取消'
          })
            .then(() => {
              request.post(`/policyAttachment/delete/${row.attachmentId}`)
                .then(res => {
                  if (res.code === 200) {
                    this.$message.success('政策附件删除成功');
                    this.fetchData();
                  } else {
                    this.$message.error(res.message || '政策附件删除失败');
                  }
                })
                .catch(err => {
                  this.$message.error('删除失败，请联系管理员');
                  console.error('删除接口异常:', err);
                });
            })
            .catch(() => {});
        },
        
        // 批量删除
        handleBatchDelete() {
          if (!this.selectedIds.length) {
            this.$message.warning('请选择要删除的记录');
            return;
          }
          
          this.$confirm(
            `确认批量删除 <span class="text-danger">${this.selectedIds.length}</span> 条政策附件吗？操作不可恢复`, 
            '警告', 
            {
              type: 'danger',
              confirmButtonText: '确认删除',
              cancelButtonText: '取消',
              dangerouslyUseHTMLString: true
            }
          )
            .then(() => {
              request.delete('/policyAttachment/delete/batch', { data: this.selectedIds })
                .then(res => {
                  if (res.code === 200) {
                    this.$message.success(`成功删除 ${this.selectedIds.length} 条政策附件`);
                    this.fetchData();
                    this.selectedIds = [];
                  } else {
                    this.$message.error(`批量删除失败: ${res.message || '未知错误'}`);
                  }
                })
                .catch(err => {
                  this.$message.error('批量删除失败，请检查网络或重试');
                  console.error('批量删除接口异常:', err);
                });
            })
            .catch(() => {});
        },
        
        // 下载附件
        downloadAttachment(row) {
          // 实现文件下载逻辑
          window.open(row.attachmentPath, '_blank');
        },
        
        // 上传前处理
        beforeUpload(file) {
          this.uploadForm.file = file;
          this.uploadForm.fileName = file.name;
          this.uploadForm.attachmentType = file.type;
          this.uploadForm.attachmentSize = file.size;
          return false; // 阻止默认上传行为
        },
        
        // 提交上传
        submitUpload() {
          if (!this.uploadForm.policyId) {
            this.$message.warning('请输入政策ID');
            return;
          }
          
          if (!this.uploadForm.uploaderId) {
            this.$message.warning('请输入上传人ID');
            return;
          }
          
          if (!this.uploadForm.uploaderName) {
            this.$message.warning('请输入上传人姓名');
            return;
          }
          
          if (!this.uploadForm.file) {
            this.$message.warning('请选择要上传的文件');
            return;
          }
          
          const formData = new FormData();
          formData.append('policyId', this.uploadForm.policyId);
          formData.append('uploaderId', this.uploadForm.uploaderId);
          formData.append('uploaderName', this.uploadForm.uploaderName);
          formData.append('file', this.uploadForm.file);
          
          request.post('/policyAttachment/upload', formData, {
            headers: {
              'Content-Type': 'multipart/form-data'
            }
          })
            .then(res => {
              if (res.code === 200) {
                this.$message.success('政策附件上传成功');
                this.uploadDialogVisible = false;
                this.fetchData();
              } else {
                this.$message.error(res.message || '政策附件上传失败');
              }
            })
            .catch(err => {
              console.error('上传接口异常:', err);
              this.$message.error('上传失败，请检查网络或文件大小限制');
            });
        },
        
        // 上传成功处理
        handleUploadSuccess(response, file, fileList) {
          // 这里不会执行，因为我们阻止了默认上传行为
        },
        
        // 上传失败处理
        handleUploadError(err, file, fileList) {
          // 这里不会执行，因为我们阻止了默认上传行为
        },
        
        // 提交编辑
        submitEdit() {
          this.$refs.editFormRef.validate(valid => {
            if (!valid) return;

            request.post('/policyAttachment/update', this.editForm)
              .then(res => {
                if (res.code === 200) {
                  this.$message.success('政策附件更新成功');
                  this.editDialogVisible = false;
                  this.fetchData();
                } else {
                  this.$message.error(res.message || '政策附件更新失败');
                }
              })
              .catch(err => {
                console.error('更新接口异常:', err);
                this.$message.error('更新失败，请检查参数或联系管理员');
              });
          });
        }
      },
      
      created() {
        this.fetchData();
      }
    };
    </script>

    <style scoped>
    /* 基础容器样式 */
    .policy-attachment-container {
      padding: 20px;
      background: #fff;
      border-radius: 8px;
      box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
    }

    /* 搜索栏样式 */
    .search-container {
      margin-bottom: 20px;
      padding: 20px;
      background-color: #f9fafc;
      border-radius: 6px;
      border: 1px solid #ebeef5;
    }

    /* 操作按钮样式 */
    .operation-buttons {
      display: flex;
      gap: 10px;
      margin-bottom: 20px;
    }

    /* 表格样式 */
    .table-container {
      overflow-x: auto;
    }

    .el-table {
      font-size: 14px;
      margin-top: 10px;
    }

    .el-table th {
      background-color: #f5f7fa;
      font-weight: 500;
      color: #333;
      text-align: center;
    }

    .el-table .cell {
      padding: 10px 8px;
      text-align: center;
    }

    /* 省略号样式 */
    .ellipsis {
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
      display: block;
    }

    /* 对话框底部样式 */
    .dialog-footer {
      display: flex;
      justify-content: flex-end;
      gap: 10px;
      padding: 15px 20px;
      border-top: 1px solid #ebeef5;
      background-color: #f9fafc;
      border-radius: 0 0 6px 6px;
    }

    /* 响应式设计 */
    @media (max-width: 1024px) {
      .el-table-column:not([fixed]) {
        min-width: 120px;
      }
    }
    </style>
    